package com.moon.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.moon.constants.MoonConstants;
import com.moon.model.UpdateFeedback;

/**
 * 系统更新工具类
 * 
 * @author jasen.hsu.cn@gmail.com
 */
public class UpdateUtil {
    /** /mnt/sdcard/download/ 是公共的下载目录 */
    public static final String  UPDATE_SAVE_FILE_NAME       = "download" + File.separator
                                                                    + "moon-%1$s.apk";

    // TODO
    private static final String GET_SERVER_VERSION_INFO_URL = MoonConstants.MOON_DOMAIN+"/mobile_user/app_update.do";

    private static final String TAG                         = UpdateUtil.class.getSimpleName();

    /**
     * 下载进度回调接口
     */
    public interface DownloadProgressCallback {
        void publish(int sizeDownloaded);
    }

    /**
     * 获取从服务端更新信息
     */
    public static UpdateFeedback checkUpdate() throws IOException {
        try {
            String body = HttpClientUtils.post(GET_SERVER_VERSION_INFO_URL,
                    assembleRequestParams(MoonConstants.APP_KEY));
            if (!TextUtils.isEmpty(body)) {
                UpdateFeedback feedback = JacksonUtils.fromJSON(body, UpdateFeedback.class);
                return feedback;
            }
        } catch (IOException e) {
            Log.e(TAG, e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }
        return null;
    }

    /**
     * 下载文件
     * 
     * @param fileUrl
     * @return 返回保存的file路径
     * @param version
     * @throws Exception
     */
    public static String downloadFile(String fileUrl, String version) throws Exception {
        return downloadFile(fileUrl, version, null);
    }

    /**
     * 下载文件
     * 
     * @param fileUrl
     * @return 返回保存的file路径
     * @param version
     * @param callback 进度回调接口
     * @throws Exception
     */
    public static String downloadFile(String fileUrl, String version,
                                      DownloadProgressCallback callback) throws Exception {
        File file = null;
        InputStream input = null;
        OutputStream output = null;
        try {
            input = HttpClientUtils.download(fileUrl);
            if (input != null) {
                file = new File(Environment.getExternalStorageDirectory(), String.format(
                        UPDATE_SAVE_FILE_NAME, version));
                output = new FileOutputStream(file);
                byte[] buf = new byte[1024];
                int totalCount = 0;
                int count;
                while ((count = input.read(buf)) != -1) {
                    totalCount += count;
                    output.write(buf, 0, count);
                    if (callback != null) {
                        callback.publish(totalCount);
                    }
                }
                output.flush();
                return file.getAbsolutePath();
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
            throw e;
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                }
            }
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }

    /**
     * 安装更新
     * 
     * @param context
     */
    public static void installApk(Context context, String filePath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(new File(filePath)),
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    /**
     * 获取当前应用版本
     * 
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        int verCode = -1;
        try {
            verCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
        return verCode;
    }

    /**
     * 获取当前应用版本名称
     * 
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
            return "1.0";
        }
    }

    /**
     * 查询条件
     * 
     * @return
     */
    private static List<NameValuePair> assembleRequestParams(String appName) {
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("key", appName));
        return params;
    }
}
